<?php

namespace MoChat\Salesman\Action;

use Hyperf\DbConnection\Db;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;

/**
 * 客户列表
 * @Controller
 */
class ClientList extends AbstractAction
{
    use ValidateSceneTrait;

    private function userType($type)
    {
        $userType = [
            0 => '未选择',
            1 => '药店',
            2 => '诊所',
            3 => '连锁',
            4 => '商业公司',
        ];
        return $userType[$type] ?? "";
    }

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesman/client", methods="POST")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $client = Db::table('client')
            ->when(!empty($data['enterprise_name']),function ($query)use ($data){
                $query->where('client.enterprise_name','like','%'.$data['enterprise_name'].'%');
            })
            ->limit(50)
            ->select([
                'client.id as clientId',
                'client.enterprise_name',
                'client.b2b_user_type',
                'client.address',
                'client.province',
                'client.city',
                'client.district',
                // Db::raw('st_distance_sphere (point (mc_client.lng, mc_client.lat),point (' . $data['lng'] . ',' . $data['lat'] . '  )) AS distance')
            ])
            // ->orderBy('distance', 'desc')
            ->paginate();
        if (!empty($client->items())) {
            $province = array_column($client->items(), 'province');
            $city = array_column($client->items(), 'city');
            $district = array_column($client->items(), 'district');
            $distIds = array_merge($province, $city, $district);
            $districtData = Db::table('district')->whereIn('id', $distIds)->pluck('name', 'id')->toArray();
            foreach ($client->items() as &$item) {
                // $item->distance = round($item->distance, 2) . '米';
                $item->address = ($districtData[$item->province] ?? "") . ($districtData[$item->city] ?? "") . ($districtData[$item->district] ?? "") . $item->address;
                $item->userType = $this->userType($item->b2b_user_type);
                unset($item->b2b_user_type,$item->province,$item->city,$item->district);
            }
            unset($item);
        }
        return $client;
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'lng' => 'required',
            'lat' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'lng.required' => '经度必填',
            'lat.required' => '纬度必填',
        ];
    }
}
